package com.example.handheld4_gsignal_app.services;

import android.content.Context;
import android.util.Log;
import com.example.handheld4_gsignal_app.network.ApiClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务管理服务 - 提供任务创建、分配、状态跟踪等功能
 */
public class TaskManagementService {
    
    private static final String TAG = "TaskManagementService";
    private Context context;
    private ApiClient apiClient;
    private Gson gson;
    
    public TaskManagementService(Context context) {
        this.context = context;
        this.apiClient = new ApiClient();
        this.gson = new Gson();
    }
    
    /**
     * 任务状态枚举
     */
    public enum TaskStatus {
        PENDING("pending"),
        IN_PROGRESS("in_progress"),
        COMPLETED("completed"),
        REJECTED("rejected"),
        CANCELLED("cancelled");
        
        private final String value;
        
        TaskStatus(String value) {
            this.value = value;
        }
        
        public String getValue() {
            return value;
        }
    }
    
    /**
     * 任务优先级枚举
     */
    public enum TaskPriority {
        LOW("low"),
        MEDIUM("medium"),
        HIGH("high"),
        URGENT("urgent");
        
        private final String value;
        
        TaskPriority(String value) {
            this.value = value;
        }
        
        public String getValue() {
            return value;
        }
    }
    
    /**
     * 任务模型
     */
    public static class Task {
        private String taskId;
        private String title;
        private String description;
        private String assigneeId;
        private String creatorId;
        private String teamId;
        private String status;
        private String priority;
        private String dueDate;
        private String relatedRecordId;
        private String relatedDeviceId;
        private List<String> tags;
        private List<String> attachments;
        private String createdAt;
        private String updatedAt;
        private String completedAt;
        
        // Getters and Setters
        public String getTaskId() { return taskId; }
        public void setTaskId(String taskId) { this.taskId = taskId; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        
        public String getCreatorId() { return creatorId; }
        public void setCreatorId(String creatorId) { this.creatorId = creatorId; }
        
        public String getTeamId() { return teamId; }
        public void setTeamId(String teamId) { this.teamId = teamId; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public String getPriority() { return priority; }
        public void setPriority(String priority) { this.priority = priority; }
        
        public String getDueDate() { return dueDate; }
        public void setDueDate(String dueDate) { this.dueDate = dueDate; }
        
        public String getRelatedRecordId() { return relatedRecordId; }
        public void setRelatedRecordId(String relatedRecordId) { this.relatedRecordId = relatedRecordId; }
        
        public String getRelatedDeviceId() { return relatedDeviceId; }
        public void setRelatedDeviceId(String relatedDeviceId) { this.relatedDeviceId = relatedDeviceId; }
        
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
        
        public List<String> getAttachments() { return attachments; }
        public void setAttachments(List<String> attachments) { this.attachments = attachments; }
        
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
        
        public String getUpdatedAt() { return updatedAt; }
        public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; }
        
        public String getCompletedAt() { return completedAt; }
        public void setCompletedAt(String completedAt) { this.completedAt = completedAt; }
    }
    
    /**
     * 任务评论模型
     */
    public static class TaskComment {
        private String commentId;
        private String taskId;
        private String userId;
        private String content;
        private String parentCommentId;
        private String createdAt;
        private String updatedAt;
        
        // Getters and Setters
        public String getCommentId() { return commentId; }
        public void setCommentId(String commentId) { this.commentId = commentId; }
        
        public String getTaskId() { return taskId; }
        public void setTaskId(String taskId) { this.taskId = taskId; }
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getParentCommentId() { return parentCommentId; }
        public void setParentCommentId(String parentCommentId) { this.parentCommentId = parentCommentId; }
        
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
        
        public String getUpdatedAt() { return updatedAt; }
        public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; }
    }
    
    /**
     * 任务创建请求
     */
    public static class CreateTaskRequest {
        private String title;
        private String description;
        private String assigneeId;
        private String teamId;
        private String priority;
        private String dueDate;
        private String relatedRecordId;
        private String relatedDeviceId;
        private List<String> tags;
        private List<String> attachments;
        
        public CreateTaskRequest(String title, String description, String teamId) {
            this.title = title;
            this.description = description;
            this.teamId = teamId;
            this.priority = TaskPriority.MEDIUM.getValue();
            this.tags = new ArrayList<>();
            this.attachments = new ArrayList<>();
        }
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        
        public String getTeamId() { return teamId; }
        public void setTeamId(String teamId) { this.teamId = teamId; }
        
        public String getPriority() { return priority; }
        public void setPriority(String priority) { this.priority = priority; }
        
        public String getDueDate() { return dueDate; }
        public void setDueDate(String dueDate) { this.dueDate = dueDate; }
        
        public String getRelatedRecordId() { return relatedRecordId; }
        public void setRelatedRecordId(String relatedRecordId) { this.relatedRecordId = relatedRecordId; }
        
        public String getRelatedDeviceId() { return relatedDeviceId; }
        public void setRelatedDeviceId(String relatedDeviceId) { this.relatedDeviceId = relatedDeviceId; }
        
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
        
        public List<String> getAttachments() { return attachments; }
        public void setAttachments(List<String> attachments) { this.attachments = attachments; }
    }
    
    /**
     * 任务更新请求
     */
    public static class UpdateTaskRequest {
        private String title;
        private String description;
        private String assigneeId;
        private String status;
        private String priority;
        private String dueDate;
        private List<String> tags;
        private List<String> attachments;
        
        // Getters and Setters
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        public String getAssigneeId() { return assigneeId; }
        public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public String getPriority() { return priority; }
        public void setPriority(String priority) { this.priority = priority; }
        
        public String getDueDate() { return dueDate; }
        public void setDueDate(String dueDate) { this.dueDate = dueDate; }
        
        public List<String> getTags() { return tags; }
        public void setTags(List<String> tags) { this.tags = tags; }
        
        public List<String> getAttachments() { return attachments; }
        public void setAttachments(List<String> attachments) { this.attachments = attachments; }
    }
    
    /**
     * 任务列表响应
     */
    public static class TaskListResponse {
        private List<Task> tasks;
        private int total;
        private int page;
        private int pageSize;
        private int totalPages;
        
        // Getters and Setters
        public List<Task> getTasks() { return tasks; }
        public void setTasks(List<Task> tasks) { this.tasks = tasks; }
        
        public int getTotal() { return total; }
        public void setTotal(int total) { this.total = total; }
        
        public int getPage() { return page; }
        public void setPage(int page) { this.page = page; }
        
        public int getPageSize() { return pageSize; }
        public void setPageSize(int pageSize) { this.pageSize = pageSize; }
        
        public int getTotalPages() { return totalPages; }
        public void setTotalPages(int totalPages) { this.totalPages = totalPages; }
    }
    
    /**
     * 回调接口
     */
    public interface TaskCallback {
        void onSuccess(Task task);
        void onError(String error);
    }
    
    public interface TaskListCallback {
        void onSuccess(TaskListResponse response);
        void onError(String error);
    }
    
    public interface CommentCallback {
        void onSuccess(TaskComment comment);
        void onError(String error);
    }
    
    public interface CommentListCallback {
        void onSuccess(List<TaskComment> comments);
        void onError(String error);
    }
    
    /**
     * 创建任务
     */
    public void createTask(CreateTaskRequest request, TaskCallback callback) {
        try {
            String requestJson = gson.toJson(request);
            Log.d(TAG, "创建任务请求: " + requestJson);
            
            apiClient.post("/api/v2/tasks", requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        Task task = gson.fromJson(response, Task.class);
                        Log.d(TAG, "任务创建成功: " + task.getTaskId());
                        callback.onSuccess(task);
                    } catch (Exception e) {
                        Log.e(TAG, "解析任务创建结果失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "任务创建失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "任务创建请求失败", e);
            callback.onError("创建请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取任务详情
     */
    public void getTask(String taskId, TaskCallback callback) {
        try {
            String url = "/api/v2/tasks/" + taskId;
            Log.d(TAG, "获取任务详情: " + taskId);
            
            apiClient.get(url, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        Task task = gson.fromJson(response, Task.class);
                        Log.d(TAG, "获取任务详情成功: " + task.getTitle());
                        callback.onSuccess(task);
                    } catch (Exception e) {
                        Log.e(TAG, "解析任务详情失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "获取任务详情失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "获取任务详情请求失败", e);
            callback.onError("获取请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新任务
     */
    public void updateTask(String taskId, UpdateTaskRequest request, TaskCallback callback) {
        try {
            String requestJson = gson.toJson(request);
            String url = "/api/v2/tasks/" + taskId;
            Log.d(TAG, "更新任务请求: " + taskId);
            
            apiClient.put(url, requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        Task task = gson.fromJson(response, Task.class);
                        Log.d(TAG, "任务更新成功: " + task.getTaskId());
                        callback.onSuccess(task);
                    } catch (Exception e) {
                        Log.e(TAG, "解析任务更新结果失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "任务更新失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "任务更新请求失败", e);
            callback.onError("更新请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取团队任务列表
     */
    public void getTeamTasks(String status, String assigneeId, String priority, 
                           int page, int pageSize, TaskListCallback callback) {
        try {
            StringBuilder url = new StringBuilder("/api/v2/tasks?");
            if (status != null) url.append("status=").append(status).append("&");
            if (assigneeId != null) url.append("assignee_id=").append(assigneeId).append("&");
            if (priority != null) url.append("priority=").append(priority).append("&");
            url.append("page=").append(page).append("&");
            url.append("page_size=").append(pageSize);
            
            Log.d(TAG, "获取团队任务列表: " + url.toString());
            
            apiClient.get(url.toString(), new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        TaskListResponse taskList = gson.fromJson(response, TaskListResponse.class);
                        Log.d(TAG, "获取团队任务列表成功，数量: " + taskList.getTasks().size());
                        callback.onSuccess(taskList);
                    } catch (Exception e) {
                        Log.e(TAG, "解析团队任务列表失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "获取团队任务列表失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "获取团队任务列表请求失败", e);
            callback.onError("获取请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取我的任务列表
     */
    public void getMyTasks(String status, int page, int pageSize, TaskListCallback callback) {
        try {
            StringBuilder url = new StringBuilder("/api/v2/tasks/my?");
            if (status != null) url.append("status=").append(status).append("&");
            url.append("page=").append(page).append("&");
            url.append("page_size=").append(pageSize);
            
            Log.d(TAG, "获取我的任务列表: " + url.toString());
            
            apiClient.get(url.toString(), new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        TaskListResponse taskList = gson.fromJson(response, TaskListResponse.class);
                        Log.d(TAG, "获取我的任务列表成功，数量: " + taskList.getTasks().size());
                        callback.onSuccess(taskList);
                    } catch (Exception e) {
                        Log.e(TAG, "解析我的任务列表失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "获取我的任务列表失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "获取我的任务列表请求失败", e);
            callback.onError("获取请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加任务评论
     */
    public void addTaskComment(String taskId, String content, String parentCommentId, CommentCallback callback) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("task_id", taskId);
            request.put("content", content);
            if (parentCommentId != null) {
                request.put("parent_comment_id", parentCommentId);
            }
            
            String requestJson = gson.toJson(request);
            String url = "/api/v2/tasks/" + taskId + "/comments";
            Log.d(TAG, "添加任务评论: " + taskId);
            
            apiClient.post(url, requestJson, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        TaskComment comment = gson.fromJson(response, TaskComment.class);
                        Log.d(TAG, "任务评论添加成功: " + comment.getCommentId());
                        callback.onSuccess(comment);
                    } catch (Exception e) {
                        Log.e(TAG, "解析任务评论结果失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "任务评论添加失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "任务评论添加请求失败", e);
            callback.onError("添加请求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取任务评论列表
     */
    public void getTaskComments(String taskId, CommentListCallback callback) {
        try {
            String url = "/api/v2/tasks/" + taskId + "/comments";
            Log.d(TAG, "获取任务评论列表: " + taskId);
            
            apiClient.get(url, new ApiClient.ApiCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        Type listType = new TypeToken<List<TaskComment>>(){}.getType();
                        List<TaskComment> comments = gson.fromJson(response, listType);
                        Log.d(TAG, "获取任务评论列表成功，数量: " + comments.size());
                        callback.onSuccess(comments);
                    } catch (Exception e) {
                        Log.e(TAG, "解析任务评论列表失败", e);
                        callback.onError("解析结果失败: " + e.getMessage());
                    }
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "获取任务评论列表失败: " + error);
                    callback.onError(error);
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "获取任务评论列表请求失败", e);
            callback.onError("获取请求失败: " + e.getMessage());
        }
    }
}